#!/bin/bash

# 定义一个函数来添加Docker仓库
add_docker_repo() {
    local os_id=$(lsb_release -is)
    local os_codename=$(lsb_release -cs)

    case "$os_id" in
        Ubuntu|Debian)
            # 使用APT
            curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
            sudo add-apt-repository \
               "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
               $os_codename \
               stable"
            ;;
        CentOS|Fedora)
            # 使用YUM/DNF
            sudo yum-config-manager \
                --add-repo \
                https://download.docker.com/linux/centos/docker-ce.repo
            ;;
        ArchLinux)
            # 使用Pacman
            # 注意：Arch Linux通常使用AUR或官方仓库中的docker包
            # 这里只是示例，可能需要手动安装或使用AUR助手
            ;;
        *)
            echo "Unsupported Linux distribution: $os_id"
            exit 1
            ;;
    esac
}

# 定义一个函数来配置Docker加速器（这里以阿里云为例）
configure_docker_mirror() {
    cat <<EOF | sudo tee /etc/docker/daemon.json
{
  "registry-mirrors": [
    "https://dockerhub.icu",
    "https://docker.awsl9527.cn",
    "https://docker.13140521.xyz",
    "https://hub.atomgit.com",
    "https://hub.gog.email",
    "https://docker.211678.top",
    "https://ung2thfc.mirror.aliyuncs.com",
    "https://docker.hlyun.org",
    "https://registry.docker-cn.com",
    "https://hub-mirror.c.163.com",
    "https://mirror.ccs.tencentyun.com"
  ]
}
EOF
    sudo systemctl daemon-reload
    sudo systemctl restart docker
}

# 安装Docker
install_docker() {
    local os_id=$(lsb_release -is)

    # 更新软件包列表
    case "$os_id" in
        Ubuntu|Debian)
            sudo apt-get update -y
            sudo apt-get install -y apt-transport-https ca-certificates curl software-properties-common
            ;;
        CentOS|Fedora)
            sudo yum install -y yum-utils device-mapper-persistent-data lvm2
            ;;
    esac

    # 添加Docker仓库
    add_docker_repo

    # 再次更新软件包列表
    case "$os_id" in
        Ubuntu|Debian)
            sudo apt-get update -y
            ;;
    esac

    # 安装Docker CE
    case "$os_id" in
        Ubuntu|Debian)
            sudo apt-get install -y docker-ce docker-ce-cli containerd.io
            ;;
        CentOS|Fedora)
            sudo yum install -y docker-ce docker-ce-cli containerd.io
            ;;
        *)
            echo "Unsupported Linux distribution for Docker installation: $os_id"
            exit 1
            ;;
    esac

    # 启动Docker服务
    sudo systemctl start docker

    # 设置Docker服务在启动时自动运行
    sudo systemctl enable docker

    # 配置Docker加速器
    configure_docker_mirror
}

# 运行安装函数
install_docker

echo "Docker安装完成，并配置了Docker加速器！"
